package cn.wujiangbo.controller.base;

import cn.wujiangbo.constants.ErrorCode;
import cn.wujiangbo.constants.SystemConstants;
import cn.wujiangbo.domain.app.AppUser;
import cn.wujiangbo.domain.system.SysUser;
import cn.wujiangbo.exception.MyException;
import cn.wujiangbo.service.app.AppUserService;
import cn.wujiangbo.util.MyTools;
import cn.wujiangbo.util.RedisCache;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @des: Controller的基础类
 * @Author 波波老师(weixin : javabobo0513)
 */
public class BaseController {

    @Resource
    private RedisCache redisCache;

    @Resource
    private AppUserService appUserService;

    /**
     * 获取APP用户昵称
     */
    public String getAppNickName() {
        Long appUserId = getAppUserId();
        if (appUserId != null) {
            AppUser one = appUserService.getById(appUserId);
            if (one != null) {
                return one.getNickName();
            }
        }
        return null;
    }

    /**
     * 获取APP用户ID
     */
    public Long getAppUserId() {
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        if (request != null) {
            String headerToken = request.getHeader("token");
            if (MyTools.hasLength(headerToken)) {
                String userInfo = redisCache.getCacheObject(SystemConstants.LOGIN_TOKEN_KEY_APP + headerToken);
                AppUser user = JSONObject.parseObject(userInfo, AppUser.class);
                return user.getId();
            } else {
                throw new MyException("您没有权限进行此操作！");
            }
        }
        return null;
    }

    /**
     * 获取登录人的信息
     *
     * @return
     */
    public SysUser getCurrentUser() {
        //获取 HttpServletRequest 对象
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        //从请求头中获取 token 值
        String token = request.getHeader("token");
        if (!MyTools.hasLength(token)) {
            throw new MyException(ErrorCode.ERROR_CODE_1002.getMessage());
        }
        String userInfoString = redisCache.getCacheObject(SystemConstants.LOGIN_TOKEN_KEY_APP + token);
        if (!MyTools.hasLength(userInfoString)) {
            throw new MyException(ErrorCode.ERROR_CODE_1002.getMessage());
        }
        SysUser sysUser = JSONObject.parseObject(userInfoString, SysUser.class);
        return sysUser;
    }

    /**
     * 获取登录人的用户ID
     *
     * @return
     */
    public Long getCurrentUserId() {
        return getCurrentUser().getId();
    }

    /**
     * 获取登录人的真实姓名
     *
     * @return
     */
    public String getCurrentUserRealName() {
        return getCurrentUser().getRealName();
    }
}
